<template>
  <div v-loading="loading" class="app-container fba_allot_order_add">
    <div class="header_title_box">
      <h2>基本信息</h2>
    </div>
    <el-form :ref="formName" inline :model="formFieldsData" :rules="rules" label-width="110px" :disabled="type === 'info'">
      <!-- 调拨单基本信息 -->
      <div class="select_form_box">
        <el-row :gutter="36">
          <el-col :span="6" :offset="0">
            <el-form-item label="调出实体仓" prop="entity_warehouse_id">
              <el-select v-model="formFieldsData.entity_warehouse_id" clearable filterable placeholder="-请选择-" class="input-with-select" @change="changeEntityWarehouseHandler">
                <el-option v-for="item in entityWarehouseList" :key="item.id" :value="item.id" :label="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="调出虚拟仓" prop="virtual_warehouse_id">
              <el-select v-model="formFieldsData.virtual_warehouse_id" clearable filterable placeholder="-请选择-" class="input-with-select" @change="changeVirtualWarehouseHandler">
                <el-option v-for="item in virtualWarehouseList" :key="item.id" :value="item.id" :label="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="FBA仓库" prop="fba_warehouse_id">
              <el-select v-model="formFieldsData.fba_warehouse_id" clearable placeholder="-请选择-" class="input-with-select">
                <el-option v-for="item in fbaWarehouseList" :key="item.id" :value="item.id" :label="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="发货类型" prop="delivery_type">
              <el-select v-model="formFieldsData.delivery_type" clearable>
                <el-option v-for="item in DICTIONARIES.deliveryType" :key="item.id" :value="item.id" :label="item.dict_data_name" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="36">
          <el-col :span="6" :offset="0">
            <el-form-item label="配送类型" prop="shipping_type">
              <el-select v-model="formFieldsData.shipping_type" clearable>
                <el-option v-for="item in DICTIONARIES.shippingType" :key="item.id" :value="item.id" :label="item.dict_data_name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="是否由客户安排发货" prop="customer_type">
              <el-select v-model="formFieldsData.customer_type" clearable>
                <el-option :value="0" label="否" />
                <el-option :value="1" label="是" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="装箱服务" prop="packing_service">
              <el-select v-model="formFieldsData.packing_service" clearable>
                <el-option v-for="item in DICTIONARIES.packingMethod" :key="item.id" :value="item.id" :label="item.dict_data_name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="增值服务" prop="value_added_services">
              <el-select v-model="formFieldsData.value_added_services" clearable>
                <el-option v-for="item in DICTIONARIES.valueAddedServices" :key="item.id" :value="item.id" :label="item.dict_data_name" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="36">
          <el-col :span="6" :offset="0">
            <el-form-item label="产品换标服务" prop="label_change_service">
              <el-select v-model="formFieldsData.label_change_service" clearable>
                <el-option v-for="item in DICTIONARIES.labelChangeService" :key="item.id" :value="item.id" :label="item.dict_data_name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="外箱贴标服务" prop="containers_label_service">
              <el-select v-model="formFieldsData.containers_label_service" clearable>
                <el-option v-for="item in DICTIONARIES.containersLabelService" :key="item.id" :value="item.id" :label="item.dict_data_name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="物流费" prop="logistics_fee">
              <el-input v-model="formFieldsData.logistics_fee" maxlength="10" placeholder="手工输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="Bill of Lading Number" prop="bill_of_lading_number">
              <el-input v-model="formFieldsData.bill_of_lading_number" maxlength="50" placeholder="手工输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="Amazon PO Id" prop="amazon_po_id">
              <el-input v-model="formFieldsData.amazon_po_id" maxlength="50" placeholder="手工输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="36">
          <el-col :span="12" :offset="0">
            <el-form-item label="特殊说明文件" prop="attachment">
              <uploadFile :file-list="fileListmark" accept-type="application/zip,application/x-zip-compressed,application/pdf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" list-type="text" @handleImageSuccess="handleFileSuccess" @beforeRemoveFile="beforeRemoveFile" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="备注" prop="notes">
              <el-input v-model="formFieldsData.notes" type="textarea" autosize placeholder="手工输入" class="wfull" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 商品信息 -->
        <div class="header_title_box">
          <h2>商品明细信息</h2>
        </div>
        <div v-if="type !== 'info'" class="operation_button_box">
          <el-button size="middle" type="primary" icon="el-icon-circle-plus-outline" @click="showAddProductsDialog">添加商品</el-button>
          <el-button size="middle" type="primary" @click="delProducts">批量删除</el-button>
        </div>
        <div v-loading="loading" class="warehouse_order_add_products mb24">
          <el-table :data="products" border fit @selection-change="tableSelectHandler">
            <el-table-column type="selection" width="51" align="center" />
            <el-table-column v-if="type !== 'info'" label="操作" align="center" width="109">
              <template slot-scope="scope">
                <span class="delete_style" style="margin: 0;" @click="delProduct(scope.row.goods_id)">删除</span>
              </template>
            </el-table-column>
            <el-table-column label="缩略图" prop="goods_pic" align="center" width="148">
              <template slot-scope="scope">
                <thund :img="scope.row.goods_pic | shopThund" />
              </template>
            </el-table-column>
            <el-table-column label="系统sku" prop="goods_code" align="center" width="182" />
            <el-table-column label="调拨数量" prop="created_by_name" align="center" width="205">
              <template slot-scope="scope">
                <el-form-item :prop="`products.${ scope.$index }.number`" class="mt22" :rules="numberRule">
                  <el-input-number v-model="scope.row.number" :precision="0" :min="1" :max="scope.row.maxNumber" placeholder="手工输入" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="托盘数量" align="center" width="205">
              <template slot-scope="scope">
                <el-form-item :prop="`products.${ scope.$index }.pallet_number`" class="mt22" :rules="numberRule">
                  <el-input-number v-model="scope.row.pallet_number" :precision="0" :min="1" :max="scope.row.number" placeholder="手工输入" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="即时库存" prop="stock" align="center" width="205" />
            <el-table-column label="中文名称" prop="goods_name" align="center" width="208" />
            <el-table-column label="英文名称" prop="goods_name_en" align="center" width="258" />
            <el-table-column label="包装类型" align="center" width="167">
              <template slot-scope="scope">
                <dic-values :dictionaries="DICTIONARIES.splitOrder" :code="scope.row.packing_method" />
              </template>
            </el-table-column>
            <el-table-column label="商品分类" prop="category_name" align="center" width="203" />
            <el-table-column label="贴标费" prop="label_price" align="center" width="205">
              <template slot-scope="scope">
                {{ getPrice(scope.row.number, serviceParams.label_price) }}
              </template>
            </el-table-column>
            <el-table-column label="打托费" prop="pallet_price" align="center" width="205">
              <template slot-scope="scope">
                {{ getPrice(scope.row.pallet_number, serviceParams.pallet_price) }}
              </template>
            </el-table-column>
            <el-table-column label="出库费" prop="outbound_price" align="center" width="205">
              <template slot-scope="scope">
                {{ getPrice(scope.row.pallet_number, serviceParams.outbound_price) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 配件信息 -->
        <div class="header_title_box">
          <h2>配件明细信息</h2>
        </div>
        <div v-if="type !== 'info'" class="operation_button_box">
          <el-button size="middle" type="primary" icon="el-icon-circle-plus-outline" @click="showAddPartsDialog">添加配件</el-button>
          <el-button size="middle" type="primary" @click="delProducts">批量删除</el-button>
        </div>
        <div v-loading="loading" class="warehouse_order_add_products">
          <el-table :data="parts" border fit @selection-change="tableSelectHandler">
            <el-table-column type="selection" width="51" align="center" />
            <el-table-column v-if="type !== 'info'" label="操作" align="center" width="109">
              <template slot-scope="scope">
                <span class="delete_style" style="margin: 0;" @click="delProduct(scope.row.goods_id)">删除</span>
              </template>
            </el-table-column>
            <el-table-column label="缩略图" prop="goods_pic" align="center" width="148">
              <template slot-scope="scope">
                <thund :img="scope.row.goods_pic | shopThund" />
              </template>
            </el-table-column>
            <el-table-column label="配件编码" prop="goods_code" align="center" width="182" />
            <el-table-column label="调拨数量" prop="created_by_name" align="center" width="205">
              <template slot-scope="scope">
                <el-form-item :prop="`products.${ scope.$index }.number`" class="mt22" :rules="numberRule">
                  <el-input-number v-model="scope.row.number" :precision="0" :min="1" :max="scope.row.stock" placeholder="手工输入" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="托盘数量" align="center" width="205">
              <template slot-scope="scope">
                <el-form-item :prop="`products.${ scope.$index }.pallet_number`" class="mt22" :rules="numberRule">
                  <el-input-number v-model="scope.row.pallet_number" :precision="0" :min="1" :max="scope.row.number" placeholder="手工输入" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="即时库存" prop="stock" align="center" width="205" />
            <el-table-column label="中文名称" prop="goods_name" align="center" width="208" />
            <el-table-column label="配件分类" prop="category_name" align="center" width="203" />
            <el-table-column label="贴标费" prop="label_price" align="center" width="205">
              <template slot-scope="scope">
                {{ getPrice(scope.row.number, serviceParams.label_price) }}
              </template>
            </el-table-column>
            <el-table-column label="打托费" prop="pallet_price" align="center" width="205">
              <template slot-scope="scope">
                {{ getPrice(scope.row.pallet_number, serviceParams.pallet_price) }}
              </template>
            </el-table-column>
            <el-table-column label="出库费" prop="outbound_price" align="center" width="205">
              <template slot-scope="scope">
                {{ getPrice(scope.row.pallet_number, serviceParams.outbound_price) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-form>
    <div class="dialog-footer-center">
      <span>
        <el-button v-if="type !== 'info'" type="primary" :loading="btnLoading" @click="handleSubmit">保存</el-button>
        <el-button :type="type !== 'info' ? 'default' : 'primary'" @click="handleCancel">{{ type === 'info' ? '返回' : '取消' }}</el-button>
      </span>
    </div>
    <products-add-dialog ref="productsAdd" :url="productUrl" />
    <products-add-dialog ref="partsAdd" :type="2" :url="partsUrl" />
  </div>
</template>

<script>
import productsAdd from '../../mixins/productAdd'
import chooseWarehouse from '../../mixins/chooseWarehouse'
import { validPrice } from '../../../../utils/validate.js'
import { fileTransform, getFileId, filterId } from '@/filters/index'
export default {
  name: 'FbaAllotOrderAdd',
  mixins: [productsAdd, chooseWarehouse],
  data() {
    return {
      id: '', // id
      info: {}, // 详情
      loading: false,
      productUrl: '/warehouse/product/list', // 商品接口url
      partsUrl: '/warehouse/parts/list', // 配件接口url
      formName: 'fbaAllotOrderForm', // form 名称
      formFieldsData: {
        entity_warehouse_id: '', // 调出实体仓
        virtual_warehouse_id: '', // 调出虚拟仓
        fba_warehouse_id: '', // 调入fba仓
        delivery_type: '', // 发货类型
        shipping_type: '', // 配送方式
        packing_service: '', // 装箱服务
        customer_type: '', // 是否由客户安排发货
        pallet_label_service: '', // 托盘贴标服务
        label_change_service: '', // 产品换标服务
        value_added_services: '', // 增值服务
        containers_label_service: '', // 外箱贴标服务,
        logistics_fee: '0.00', // 物流费
        amazon_po_id: '', // Amazon PO Id
        bill_of_lading_number: '', // Bill of Lading Number
        attachment: '', // 特殊说明文件
        notes: '', // 备注
        products: [] // 商品列表
      },
      rules: {
        entity_warehouse_id: [
          {
            required: true,
            message: '请选择实体仓',
            trigger: ['change', 'blur']
          }
        ], // 实体仓
        virtual_warehouse_id: [
          {
            required: true,
            message: '请选择调出虚拟仓',
            trigger: ['change', 'blur']
          }
        ], // fba仓
        fba_warehouse_id: [
          {
            required: true,
            message: '请选择fba仓',
            trigger: ['change', 'blur']
          }
        ], // 发货类型
        delivery_type: [
          {
            required: true,
            message: '请选择发货类型',
            trigger: ['change', 'blur']
          }
        ], // 配送方式
        shipping_type: [
          {
            required: true,
            message: '请选择配送方式',
            trigger: ['change', 'blur']
          }
        ], // 装箱服务
        packing_service: [
          {
            required: true,
            message: '请选择装箱服务',
            trigger: ['change', 'blur']
          }
        ], // 是否由客户安排发货
        customer_type: [
          {
            required: true,
            message: '请选择是否由客户安排发货',
            trigger: ['change', 'blur']
          }
        ], // 托盘贴标服务
        pallet_label_service: [
          {
            required: true,
            message: '请选择托盘贴标服务',
            trigger: ['change', 'blur']
          }
        ], // 产品换标服务
        label_change_service: [
          {
            required: true,
            message: '请选择产品换标服务',
            trigger: ['change', 'blur']
          }
        ], // 增值服务
        value_added_services: [
          {
            required: true,
            message: '请选择增值服务',
            trigger: ['change', 'blur']
          }
        ],
        // 外箱贴标服务
        containers_label_service: [
          {
            required: true,
            message: '请选择外箱贴标服务',
            trigger: ['change', 'blur']
          }
        ],
        // 物流费
        logistics_fee: [
          {
            required: true,
            message: '请输入物流费',
            trigger: ['blur']
          },
          {
            validator(rule, value, callback) {
              if (!validPrice(value)) {
                callback(new Error('物流费必须是数字且保留两位小数'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        amazon_po_id: [
          { required: false, message: '请输入Amazon PO Id', trigger: 'blur' },
          { max: 50, message: 'Amazon PO Id必须在50个字符以内', trigger: 'blur' }
        ],
        bill_of_lading_number: [
          { required: false, message: '请输入Bill of Lading Number', trigger: 'blur' },
          { max: 50, message: 'Bill of Lading Number必须在50个字符以内', trigger: 'blur' }
        ],
        notes: [
          { max: 500, message: '备注必须在500个字符以内', trigger: 'blur' }
        ]
      },
      numberRule: [
        { required: true, message: '请输入数量', trigger: ['change', 'blur'] }
      ],
      btnLoading: false,
      fbaWarehouseList: [], // fba 仓库列表
      // 字典
      DICTIONARIES: {
        deliveryType: [], // 发货类型
        shippingType: [], // 配送类型
        packingMethod: [], // 装箱方式
        palletLabelService: [], // 托盘贴标服务
        labelChangeService: [], // 产品换标服务
        valueAddedServices: [], // 增值服务
        containersLabelService: [], // 外箱贴标服务
        splitOrder: [
          {
            code: 1,
            name: '普通商品'
          },
          {
            code: 2,
            name: '多箱包装'
          }
        ]
      },
      serviceParams: {}, // 系统参数
      fileListmark: [], // 文件列表,
      type: 'add'
    }
  },
  computed: {
    products() {
      return this.formFieldsData.products.filter((e) => e.type === 1)
    },
    parts() {
      return this.formFieldsData.products.filter((e) => e.type === 2)
    }
  },
  watch: {
    $route(router) {
      this.checkRouterHasId(router)
    }
  },
  created() {
    const vm = this
    vm.checkRouterHasId(vm.$route)
    vm.getFBAWarehouseList() // 获取fba仓库
    vm.getDictionaries() // 获取字典
    vm.getServiceParams() // 获取系统参数
    const dataObj = window.localStorage.getItem('fbaAllotOrder')
    if (dataObj) {
      vm.formFieldsData = JSON.parse(dataObj)
      if (vm.formFieldsData.entity_warehouse_id) {
        vm.getVirtualWarehouseList()
      }
    }
  },
  beforeDestroy() {
    if (!this.$route.params.id) {
      window.localStorage.setItem('fbaAllotOrder', JSON.stringify(this.formFieldsData))
    }
  },
  methods: {
    // 获取费用
    getPrice(number = 0, price) {
      const vm = this
      return +vm.$computed.accMul(number, price).toFixed(2)
    },
    // 获取系统参数
    getServiceParams() {
      const vm = this
      // vm.$http.get('/fba-allot-order/service-fee').then((res) => {
      //   vm.serviceParams = res.data
      // })
      vm.$http.get('/config/fbaAllotOrderConfig').then(res => {
        vm.serviceParams = res.data.fbaAllotOrderConfig
      })
    },
    // 修改实体仓handler
    changeEntityWarehouseHandler() {
      const vm = this
      vm.formFieldsData.virtual_warehouse_id = ''
      vm.formFieldsData.products = []
      vm.getVirtualWarehouseList()
    },
    // 修改虚拟仓库handler
    changeVirtualWarehouseHandler() {
      const vm = this
      vm.formFieldsData.products = [] // 商品是根据虚拟仓选择，所以也清空
    },
    // 获取字典列表
    getDictionaries() {
      const vm = this
      const dicParams = [
        {
          type: 'delivery_type',
          name: '发货类型',
          key: 'deliveryType'
        },
        {
          type: 'shipping_type',
          name: '配送方式',
          key: 'shippingType'
        },
        {
          type: 'packing_method',
          name: '装箱服务',
          key: 'packingMethod'
        },
        {
          type: 'pallet_label_service',
          name: '托盘贴标服务',
          key: 'palletLabelService'
        },
        {
          type: 'label_change_service',
          name: '产品换标服务',
          key: 'labelChangeService'
        },
        {
          type: 'value_added_services',
          name: '增值服务',
          key: 'valueAddedServices'
        },
        {
          type: 'containers_label_service',
          name: '外箱贴标服务',
          key: 'containersLabelService'
        }
      ]
      const promiseArr = dicParams.map((e) => {
        return new Promise((resolve, reject) => {
          vm.$http
            .get(`/getListType/${e.type}`)
            .then((res) => {
              resolve({
                data: res.data.data,
                key: e.key
              })
            })
            .catch((err) => {
              reject(err)
            })
        })
      })
      Promise.all(promiseArr).then((res) => {
        res.forEach((e) => {
          vm.DICTIONARIES[e.key] = e.data
        })
      })
    },
    // 获取fba仓库
    getFBAWarehouseList() {
      const vm = this
      const params = {
        page: 1,
        limit: 100000000,
        type: 4, // 1-实体仓 2-虚拟仓 3-残品仓 4-FBA仓
        is_active: 1
      }
      vm.$http.get('/warehouse', { params }).then((res) => {
        vm.fbaWarehouseList = res.data
      })
    },
    // 检查路由是否有id
    checkRouterHasId(router) {
      const vm = this
      const id = router.params.id
      vm.type = router.params.type
      if (id) {
        vm.id = id
        vm.getInfo()
      }
    },
    // 获取详情
    getInfo() {
      const vm = this
      vm.loading = true
      vm.$http
        .get(`/fba-allot-order/${vm.id}`)
        .then((res) => {
          vm.info = res.data
          vm.formFieldsData.entity_warehouse_id = vm.info.entity_warehouse_id // 调出实体仓
          vm.formFieldsData.virtual_warehouse_id = vm.info.virtual_warehouse_id // 调出虚拟仓
          vm.formFieldsData.fba_warehouse_id = vm.info.fba_warehouse_id // 调入fba仓
          vm.formFieldsData.delivery_type = vm.info.delivery_type // 发货类型
          vm.formFieldsData.shipping_type = vm.info.shipping_type // 配送方式
          vm.formFieldsData.packing_service = vm.info.packing_service // 装箱服务
          vm.formFieldsData.customer_type = vm.info.customer_type // 是否由客户安排发货
          vm.formFieldsData.pallet_label_service = vm.info.pallet_label_service // 托盘贴标服务
          vm.formFieldsData.label_change_service = vm.info.label_change_service // 产品换标服务
          vm.formFieldsData.value_added_services = vm.info.value_added_services // 增值服务
          vm.formFieldsData.containers_label_service =
            vm.info.containers_label_service // 外箱贴标服务,
          vm.formFieldsData.logistics_fee = vm.info.logistics_fee // 物流费
          vm.formFieldsData.bill_of_lading_number = vm.info.bill_of_lading_number // 物流费
          vm.formFieldsData.amazon_po_id = vm.info.amazon_po_id //
          vm.formFieldsData.notes = vm.info.notes // 备注
          vm.formFieldsData.attachment = vm.info.attachment // 特殊说明文件
          const parts = vm.info.parts || []
          vm.formFieldsData.products = vm.info.products.concat(parts) // 商品列表
          vm.fileListmark = fileTransform(vm.info.attachment)
          vm.loading = false

          vm.getVirtualWarehouseList(() => {
            vm.getStockInWarehouse(vm.formFieldsData.products)
          })
        })
        .catch(() => {
          vm.loading = false
        })
    },
    // 获取商品在虚拟仓库的即时库存
    getStockInWarehouse(arr) {
      const vm = this
      vm.productLoading = true
      const promiseAll = arr.map((e) => {
        return new Promise((resolve, reject) => {
          const virtualWarehouse = vm.virtualWarehouseList.find(e => e.id === vm.formFieldsData.virtual_warehouse_id)
          const params = {
            goods_code: e.goods_code,
            warehouse: virtualWarehouse.name
          }
          vm.$http
            .get('/stock', { params })
            .then((res) => {
              const data = res.data[0] || { available_stock: 0 }
              e['stock'] = data.available_stock
              e.maxNumber = e.stock + e.number
              resolve(e)
            })
            .catch((err) => {
              reject(err)
            })
        })
      })
      Promise.all(promiseAll)
        .then((res) => {
          vm.formFieldsData.products = res
          vm.productLoading = false
        })
        .catch((err) => {
          console.log('err-------------------')
          console.log(err)
          vm.productLoading = false
        })
    },
    // 显示添加产品dialog
    showAddProductsDialog() {
      const vm = this
      if (!vm.formFieldsData.virtual_warehouse_id) {
        vm.$message.error('请先选择出库虚拟仓!')
        return
      }
      vm.$refs.productsAdd.show({
        params: {
          id: vm.formFieldsData.virtual_warehouse_id,
          type: 2,
          is_disable: 1
        },
        success({ data }) {
          vm.setProducts(data)
        }
      })
    },
    // 显示添加产品dialog
    showAddPartsDialog() {
      const vm = this
      if (!vm.formFieldsData.virtual_warehouse_id) {
        vm.$message.error('请先选择出库虚拟仓!')
        return
      }
      vm.$refs.partsAdd.show({
        params: {
          id: vm.formFieldsData.virtual_warehouse_id,
          type: 2,
          is_disable: 1
        },
        success({ data }) {
          vm.setParts(data)
        }
      })
    },
    // 设置产品列表
    setProducts(data) {
      const vm = this
      data.forEach(e => {
        const index = vm.formFieldsData.products.findIndex(ele => ele.goods_id === e.id)
        if (index > -1) {
          vm.formFieldsData.products.splice(index, 1)
        }
        const item = {
          goods_id: e.id,
          goods_code: e.code,
          goods_name: e.name_ch,
          goods_name_en: e.name_en,
          category_name: e.category_name,
          goods_pic: e.image_url,
          packing_method: e.packing_method,
          stock: +e.available_stock, // 即时库存
          allot_number: 1,
          pallet_number: 1,
          number: 1,
          type: 1
        }
        vm.formFieldsData.products.push(item)
      })
      // vm.$set(vm.formFieldsData, 'products', products)
    },
    // 设置配件列表
    setParts(data) {
      const vm = this
      data.forEach(e => {
        const index = vm.formFieldsData.products.findIndex(ele => ele.goods_id === e.id)
        if (index > -1) {
          vm.formFieldsData.products.splice(index, 1)
        }
        const item = {
          goods_id: e.id,
          goods_code: e.code,
          goods_name: e.name_ch,
          goods_name_en: '',
          category_name: e.category_name,
          goods_pic: e.image_url,
          packing_method: '',
          stock: +e.number, // 即时库存
          allot_number: 1,
          type: 2,
          pallet_number: 1,
          number: 1
        }
        vm.formFieldsData.products.push(item)
      })
    },
    // 取消
    handleCancel() {
      const vm = this
      vm.$refs[vm.formName].resetFields()
      vm.formFieldsData.products = []
      vm.$router.go(-1)
    },
    // 确认
    handleSubmit() {
      const vm = this
      vm.$refs[vm.formName].validate((valid) => {
        if (valid) {
          if (vm.formFieldsData.products.length > 0) {
            const params = Object.assign({}, vm.formFieldsData)
            params.products = params.products.map((e) => {
              e['label_price'] = e.number * vm.serviceParams.label_price
              e['pallet_price'] =
                e.pallet_number * vm.serviceParams.pallet_price
              e['outbound_price'] =
                e.pallet_number * vm.serviceParams.outbound_price
              return e
            })
            vm.id ? vm.editAllotOrder(params) : vm.addAllotOrder(params)
          } else {
            vm.$message.error('请选择添加至少一个商品')
          }
        }
      })
    },
    // 添加入库单
    addAllotOrder(params) {
      const vm = this
      vm.btnLoading = true
      vm.$http
        .post('/fba-allot-order', params)
        .then((res) => {
          vm.$message.success('添加成功')
          vm.handleCancel()
          vm.btnLoading = false
        })
        .catch(() => {
          vm.btnLoading = false
        })
    },
    // 编辑入库单
    editAllotOrder(params) {
      const vm = this
      vm.btnLoading = true
      vm.$http
        .put(`/fba-allot-order/${vm.id}`, params)
        .then((res) => {
          vm.$message.success('编辑成功')
          vm.handleCancel()
          vm.btnLoading = false
        })
        .catch(() => {
          vm.btnLoading = false
        })
    },
    handleFileSuccess({ name, url }) {
      const vm = this
      vm.fileListmark.push({ name, url })
      vm.formFieldsData.attachment = getFileId(
        vm.fileListmark
      )
    },
    beforeRemoveFile(file) {
      const vm = this
      this.fileListmark = filterId(this.fileListmark, file)
      vm.formFieldsData.attachment = getFileId(
        this.fileListmark
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.fba_allot_order_add {
  .dialog-footer-center {
    margin: 46px 0 0;
  }
}
.fba_allot_order_add .select_form_box ::v-deep .el-form-item__label {
  line-height: 14px;
}
.fba_allot_order_add .select_form_box ::v-deep .el-form-item__content {
  vertical-align: middle;
}
</style>
